﻿using Common;
using Model;
using System;
using System.Collections.Generic;
using WebSocket4Net;

namespace Bussiness
{
    public class SYN
    {
        private WebSocket _WebSocketClient;
        private UI _UI = new UI();
        private string _URL;

        public SYN(string url, UI ui)
        {
            _WebSocketClient = new WebSocket(url);
            _URL = url;
            _UI = ui;
        }

        public void ConnectServer()
        {
            _WebSocketClient.Opened += WebSocketClient_Opened;
            _WebSocketClient.MessageReceived += WebSocketClient_MessageReceived;
            _UI._DeviceMessageQueue.Enqueue(new DeviceMessage()
            {
                Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                Title = "数据中心连接",
                Content = "连接websocket【" + _URL + "】..."
            });
            _WebSocketClient.Open();
        }

        private void WebSocketClient_Opened(object sender, EventArgs e)
        {
            _UI._DeviceMessageQueue.Enqueue(new DeviceMessage()
            {
                Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                Title = "数据中心连接",
                Content = "连接websocket【"+ _URL + "】成功"
            });
        }

        private void WebSocketClient_MessageReceived(object sender, MessageReceivedEventArgs e)
        {
            _UI._DeviceMessageQueue.Enqueue(new DeviceMessage()
            {
                Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                Title = "数据中心响应",
                Content = e.Message
            });
        }

        public void SendScadaData(List<ScadaData> scadaDataList)
        {
            foreach(var scadaData in scadaDataList)
            {
                scadaData.HasUp = true;
            }

            string json = JSON.SerializeObject(scadaDataList);
            Result result = Send(json);
            _UI._DeviceMessageQueue.Enqueue(new DeviceMessage()
            {
                Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                Title = "发送采集数据",
                Content = (result.Success?"成功":("失败:"+result.Msg))+" "+json
            });
        }

        public Result Send(string message)
        {
            Result result = new Result();

            try
            {
                _WebSocketClient.Send(message);
                result.Success = true;
            }
            catch(Exception ex)
            {
                result.Msg = ex.ToString();
            }

            return result;
        }
    }
}
